package client;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;

import server.Message;
import client.ClientLib.ClientType;
import client.ClientLib.FailedConnectException;
import client.ClientLib.OnSub;

public class SubFile {

	private static final int HEADER_SIZE = 124 + 14;

	private static class WriteFile implements OnSub {

		private boolean headerWritten = false;
		private RandomAccessFile f;
		private int count = 0;

		public WriteFile(String filename) {
			try {
				f = new RandomAccessFile(new File(filename), "rw");
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}

		@Override
		public void onSubReceive(Message m) {
			ByteBuffer b = ByteBuffer.wrap(m.rawData);
			long l = b.getLong();
			long o = b.getLong();
			byte[] header = new byte[HEADER_SIZE];
			b.get(header);
			byte[] data = new byte[m.rawData.length - 16 - HEADER_SIZE];
			b.get(data);
			try {
				/*if (!headerWritten) {
					f.seek(0);
					f.write(header);
					headerWritten = true;
				}*/
				f.seek(o);
				f.write(data);
				count++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		String host = (args.length > 0) ? args[0] : "localhost";
		int port = (args.length > 1) ? Integer.parseInt(args[1]) : 15000;
		int numClients = (args.length > 2) ? Integer.parseInt(args[2]) : 1;
		String tag = (args.length > 3) ? args[3] : "c";
		
		ClientLib[] clients = new ClientLib[numClients];
		WriteFile[] writers = new WriteFile[numClients];
		
		for (int i = 0; i < clients.length; i++) {
			clients[i] = new ClientLib(tag + i, host, port, ClientType.SUBSCRIBER);
			writers[i] = new WriteFile("bitmap2-" + tag + i + ".bmp");
			try {
				clients[i].subscribe("file", writers[i]);
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (FailedConnectException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			Thread.sleep(30000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		for (int i = 0; i < writers.length; i++) {
			System.out.println("w" + i + ": " + writers[i].count);
		}
		System.exit(0);
	}
}
